package com._430haus.VLC;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;

public class VLCLauncher {
	

	public static void launchVideo(final String videoLocation) throws IOException, InterruptedException {
 
		VLCLauncher obj = new VLCLauncher();
		
		String file = "file:///" + "\"" + videoLocation + "\"";
		String fullscreen = "--fullscreen";
		//String fullscreen = "";
		String commands = file + " " + fullscreen;
		String command = "C:/Program Files (x86)/VideoLAN/VLC/vlc.exe" + " " + commands;
 
		while(isVLCRunning()){
			if(!killVLC()){
				break;
			}
		}
		
		if(!isVLCRunning()){
			String output = obj.executeCommand(command);
		}
		
		
 
	}
	
	private String executeCommand(String command) throws IOException, InterruptedException {
		 
		StringBuffer output = new StringBuffer();
 
		Process p;
			p = Runtime.getRuntime().exec(command);
			p.waitFor();
			BufferedReader reader = 
                            new BufferedReader(new InputStreamReader(p.getInputStream()));
 
                        String line = "";			
			while ((line = reader.readLine())!= null) {
				output.append(line + "\n");
			}
 
		return output.toString();
 
	}
	
	public static boolean killVLC(){
		boolean success = true;
		try {
			Runtime.getRuntime().exec("taskkill /IM " + "vlc.exe");
		} catch (IOException e) {
			e.printStackTrace();
			success = false;
		}
		return success;
	}
	
	public static boolean isVLCRunning(){
		boolean isRunning = false;
		
		String line;
		try {
		    Process proc = Runtime.getRuntime().exec("wmic.exe");
		    BufferedReader input = new BufferedReader(new InputStreamReader(proc.getInputStream()));
		    OutputStreamWriter oStream = new OutputStreamWriter(proc.getOutputStream());
		    oStream .write("process where name='vlc.exe'");
		    oStream .flush();
		    oStream .close();
		    while ((line = input.readLine()) != null) {
		        if(line.contains("vlc.exe") && !line.contains("wmic")){
		        	isRunning = true;
		        }
		    }
		    input.close();
		} catch (IOException ioe) {
		    ioe.printStackTrace();
		}
		
		return isRunning;
	}

}
